local require = require
local log = require("core.log")
local dispatcher = require("dispatcher")
local call_utils = require("utils.call_utils")
local pcall = pcall
local pairs = pairs
local ipairs = ipairs
local ngx = ngx
local config = require("conf.config")
local tab_nkeys = require("table.nkeys")
local insert = table.insert
local table_new = require("table.new")
local json = require("cjson.safe")

local _M = {}

local plugins = table_new(20,0)

local function install_plugins()
    local plugin_list = config.get("plugins")
    --local plugin = require("plugins.prometheus")
    --insert(plugins,plugin)
    for _, file_name in ipairs(plugin_list) do
        local ok, plugin = pcall(require, "plugins." .. file_name)
        if not ok then
            log.error("failed to install plugin [plugins.", file_name, "]: ", plugin)
        else
            insert(plugins,plugin)
            local func = plugin["do_in_init"]
            if func then
                func()
            end
            log.notice("install plugin:", plugin.name)
        end
    end
end

function _M.init()
    log.info("ctx init")
    install_plugins()
end

function _M.init_worker()
    log.info("ctx init worker")
    call_utils.call(plugins, "do_in_init_worker")
end

-- 从上下文中获取dispatcher
function _M.get_dispatcher()
    return dispatcher:new(plugins)
end

function _M.plugins()
    return plugins
end

return _M
